package com.lwx.chapter9;

public class NumArray {
    private int[] data;
    private int[] tree;
    public NumArray(int[] nums) {
        data = new int[nums.length];
        tree = new int[4 * nums.length];
        for (int i = 0; i < nums.length; i++) {
            data[i] = nums[i];
        }
        buildSegmentTree(0, 0 , data.length-1);
    }

    //构建以treeIndex为根节点的线段树，tree[treeIndex]代表的是data[l...r]的和
    private void buildSegmentTree(int treeIndex , int l , int r){
        if(l == r){
            tree[treeIndex] = data[l];
            return;
        }
        int mid = l+ (r-l)/2;
        int leftIndex = leftChild(treeIndex);
        int rightIndex = rightChild(treeIndex);
        buildSegmentTree(leftIndex,l, mid);
        buildSegmentTree(rightIndex, mid+1, r);
        tree[treeIndex] = tree[leftIndex] + tree[rightIndex];
    }

    public int query(int queryL, int queryR){
        if(queryL < 0 || queryL > data.length-1 ||queryR < 0 || queryR > data.length-1 || queryL > queryR){
            throw new IllegalArgumentException("queryL or queryR is out of bound.Index should not less than zero or bigger than the lenght of data");
        }
        return query(0, 0, data.length-1, queryL, queryR);
    }

    private int query(int treeIndex, int l, int r, int queryL, int queryR){
        if(queryL == l && queryR == r){
            return tree[treeIndex];
        }
        int mid = l + (r - l)/2;
        int leftIndex = leftChild(treeIndex);
        int rightIndex = rightChild(treeIndex);

        if(queryL >= mid + 1){
            //只查询右子树
            return query(rightIndex , mid+1 , r , queryL , queryR);
        }else if(queryR <= mid){
            //只查询左子树
            return query(leftIndex , l , mid , queryL , queryR);
        }else {
            //左右子树都查询
            return query(leftIndex , l , mid, queryL , mid) + query(rightIndex , mid + 1, r , mid+1 , queryR);
        }

    }


    public int sumRange(int i, int j) {
        return query(i,j);
    }


    /**
     * 获取完全二叉树的左孩子索引
     * @param index
     * @return
     */
    public int leftChild(int index){
        return  2*index + 1;
    }

    /**
     * 获取完全二叉树的右孩子索引
     * @param index
     * @return
     */
    public int rightChild(int index){
        return  2*index + 2;
    }
}
